<script lang="ts" setup>
  import {ref, toRefs, watch,} from 'vue'
  import AuthorizeDrawer from '../role/AuthorizeDrawer.vue';
  import { getDataPermissionList, updateUserDataPermission } from '/@/api/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  
  const { createMessage } = useMessage();
  
  const loading = ref(false)
  
  const props = defineProps({
    visible: Boolean,
    user: Object
  })
  
  const emits = defineEmits(['update:visible', 'success'])
  
  const {visible: vis, user} = toRefs(props)
  
  let treeData = ref([]);
  let treeDataSelected = ref([])
  async function getDataListAction() {
    loading.value = true;
    const { data } = await getDataPermissionList({});
    loading.value = false;
    function formatMenuTree(s: any[]) {
      let t = [] as any;
      if (!s || s.length == 0) return undefined;
      s.forEach(e => {
        t.push({
          label: e.name,
          value: e.dataPermissionId,
          children: formatMenuTree(e.children),
        })
      })
      return t;
    }
    treeData.value = formatMenuTree(data);
    treeDataSelected.value = user?.value?.dataPermissionModelList?.map(e => e.dataPermissionId);
  }
  
  watch(vis, nv => {
    if(nv) {
      getDataListAction();
    }
  }, {immediate: true})
  
  const successHandler = async (p) => {
    loading.value = true;
    const { respCode, respMsg } = await updateUserDataPermission({userId: user?.value?.id, dataPermissionIds: p})
    loading.value = false;
    if(respCode == 200) {
      createMessage({
        message: respMsg,
      })
      emits('update:visible', false)
      emits('success')
    }
  }
  
  const cancelHandler = () => {
    emits('update:visible', false)
  }
  </script>
  
  <template>
    <AuthorizeDrawer 
      v-model:visible='vis' 
      :tree-data="treeData" 
      title="数据权限"
      :selected='treeDataSelected'
      :loading="loading"
      @success='successHandler'
      @cancel='cancelHandler'/>
  </template>
  
  <style lang="less"></style>